import { useState, useEffect } from 'react';
import '../scss/App.scss';
import { TodoListO, Replay } from '@react-vant/icons';
import summery from '../axiosAPI/yg';
import { Popup, Pagination } from 'react-vant';
import { useNavigate } from 'react-router-dom'; 

function Achievement() {
    let navigate = useNavigate();
    // 初始化状态
    let [name, setname] = useState('');
    let [time, settime] = useState('');
    let [list, setlist] = useState([]);
    let [studen, setstudent] = useState([]);
    const [visible1, setVisible1] = useState(false);
    const [page, setPage] = useState(1);
    const [totalItems, setTotalItems] = useState(0);
    const [flag, setflag] = useState(false);
    const [id, setid] = useState('');

    // 获取数据函数
    let getfino = async () => {
        let res = await summery.getdata(page, name, time);
        const students = await summery.getstudent();
        setlist(res.data);
        setTotalItems(res.total);
        console.log(students.data);
        
        setstudent(students.data);
    };

    // 监听 page, name, time 的变化来重新获取数据
    useEffect(() => {
        getfino();
    }, [page, name, time]); // 确保 page, name, time 的变化会触发数据更新

    const formatTime = (timeArray) => {
        if (timeArray && timeArray.length === 2) {
            const formatDate = (timestamp) => {
                const date = new Date(timestamp);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hour = String(date.getHours()).padStart(2, '0');
                const minute = String(date.getMinutes()).padStart(2, '0');
                return `${year}-${month}-${day} ${hour}:${minute}`;
            };
            const startTime = formatDate(timeArray[0]);
            const endTime = formatDate(timeArray[1]);
            return { startTime, endTime };
        }
        return { startTime: 'N/A', endTime: 'N/A' };
    };

    let calculateStudentCount = (classids) => {
        console.log('试卷表',classids);
        if (!Array.isArray(classids)) {
            console.error("classids is not an array:", classids);
            return 0;
        }
        if (!Array.isArray(studen)) {
            console.error("studen is not an array:", studen);
            return 0;
        }
        return studen.filter(ele => classids.includes(ele.clazz._id.toString())).length;
    };

    let change = (flags) => {
        setflag(!flags);
    };

    let saveFlagChange = async () => {
        await summery.upflag(id, flag);
        setid('');
        setflag(false);
        setVisible1(false);
        getfino();
    };

    return (
        <div id='achievement'>
            <div className='top'>
                <input className='name' type="text" placeholder='请输入考试名称' value={name} onChange={(e) => setname(e.target.value)} />
                <select className='time' onChange={(e) => settime(e.target.value)}>
                    <option value="">==请选试卷状态==</option>
                    <option value="wait">待考试</option>
                    <option value="equal">考试中</option>
                    <option value="complete">已完成</option>
                </select>
                <button className='search' onClick={() => getfino()}><TodoListO fontSize={14} />查询</button>
                <button className='reset' onClick={() => {
                    setname('');
                    settime('');
                    getfino();
                }}>
                    <Replay fontSize={14} />重置
                </button>
            </div>

            <div className='main'>
                <table border={1} cellSpacing={0} style={{ width: "100%" }}>
                    <thead>
                        <tr style={{ height: "30px", backgroundColor: "#F6F9FF" }}>
                            <th style={{ width: "200px" }}>试卷名称</th>
                            <th style={{ width: "200px" }}>试卷份数</th>
                            <th style={{ width: "200px" }}>考试总分</th>
                            <th style={{ width: "200px" }}>考试开始时间</th>
                            <th style={{ width: "200px" }}>考试结束时间</th>
                            <th style={{ width: "200px" }}>参考班级数</th>
                            <th style={{ width: "200px" }}>参考人数</th>
                            <th style={{ width: "200px" }}>状态</th>
                            <th style={{ width: "200px" }}>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {list.map(item => {
                            const { startTime, endTime } = formatTime(item.time);
                            const studentcount = calculateStudentCount(item.class.map(ele => ele._id));
                            return (
                                <tr key={item._id} style={{ textAlign: "center" }}>
                                    <td>{item.name}</td>
                                    <td>{item.questions.length} 份</td>
                                    <td>{item.out}</td>
                                    <td>{startTime}</td>
                                    <td>{endTime}</td>
                                    <td>{item.class.length}</td>
                                    <td>{studentcount || 0}</td>
                                    <td>{item.flag ? "公示中" : "阅卷中"}</td>
                                    <td>
                                        <button style={{ width: "100px", border: "none", backgroundColor: "#fff", color: "#5BB4FF" }} onClick={() => navigate('/home/show')}>阅卷情况</button>
                                        <button style={{ width: "100px", border: "none", backgroundColor: "#fff", color: "#5BB4FF" }} onClick={() => { setVisible1(true); change(item.flag); setid(item._id); }}>
                                            {item.flag ? '撤销公示' : "成绩公示"}
                                        </button>
                                    </td>
                                </tr>
                            );
                        })}
                    </tbody>
                </table>
            </div>

            <div>
                <Pagination value={page} onChange={(val) => setPage(val)} totalItems={totalItems} itemsPerPage={5} />
            </div>

            <Popup visible={visible1} onClose={() => setVisible1(false)}>
                <div style={{ padding: '30px 50px' }}>
                    <p>
                        您确定要{flag ? <>公示</> : <>撤销</>}该考核成绩吗，公示之后考生将可以在成绩
                        查询中，查看本次考试成绩
                    </p>
                    <div style={{ width: "100%", textAlign: "center", marginTop: "10px" }}>
                        <button style={{ width: "70px", height: "30px", border: "none", borderRadius: "5px", backgroundColor: "#40A9FF" }} onClick={saveFlagChange}>保存</button>
                        <button style={{ width: "70px", height: "30px", borderRadius: "5px", backgroundColor: "#fff", marginRight: "10px" }} onClick={() => setVisible1(false)}>取消</button>
                    </div>
                </div>
            </Popup>
        </div>
    );
}

export default Achievement;
